import { _decorator, Color, Component, Label, Node, Prefab, RichText, Sprite, Tween, tween, UIOpacity, v3, Vec3 } from 'cc';
import { GameData } from '../Data/GameData';
import { UserData } from '../Data/UserData';
import { RichTextAutoFontSize } from '../Tools/RichTextAutoResize';
import Tools from '../Tools/Tools';
import { Url } from '../Tools/Url';
import LocalizedLabel from '../Tools/i18n/LocalizedLabel';
import { PageHome } from '../src/ui/page/page.home';
import { AudioMgr } from './AudioMgr';
import { BoardMgr } from './BoardMgr';
import { GameMgr } from './GameMgr';
import PoolMgr from './PoolMgr';
import ServiceAPI from '../src/api/service.api';
import InitData from '../game/InitData';
const { ccclass, property } = _decorator;

@ccclass('UIMgr')
export class UIMgr extends Component {

    /** 单例模式 */
    private static _ins: UIMgr;
    constructor() {
        super();
        UIMgr._ins = this;
    }
    public static get ins(): UIMgr {
        if (!UIMgr._ins) {
            UIMgr._ins = new UIMgr();
        }
        return UIMgr._ins;
    }
    @property(Prefab)
    wordPre: Prefab = null;
    /** homepage */
    @property(PageHome)
    homePage: PageHome = null;
    /** 背景 */
    @property(Node)
    background: Node = null;
    /** 当前钱数Label */
    @property(Label)
    curCashLabel: Label = null;
    /** 当前关卡Label */
    @property(Label)
    curLevelLabel: Label = null;
    /** 对话框富文本 */
    @property(RichText)
    dialogLabel: RichText = null;
    /** 划词提示容器 */
    @property(Node)
    condContainer: Node = null;
    /** 划词提示文本 */
    @property(Label)
    condLabel: Label = null;
    /** 特效节点容器 */
    @property(Node)
    effectsContainer: Node = null;
    /** 答案节点容器 */
    @property(Node)
    answerNodeContainer: Node = null;
    /** 左上角钱icon */
    @property(Node)
    tarCashIcon: Node = null;
    /** 抽奖配置 */
    lotteryData: any = null;
    /** 抽奖进度 */
    @property(Sprite)
    lotteryProgress: Sprite = null;
    /** 抽奖进度文字 */
    @property(Label)
    lotteryProgressLabel: Label = null;
    /** 抽奖提示文字 */
    @property(RichText)
    lottoryLabel: RichText = null;
    /** 抽奖icon */
    @property(Node)
    lotteryIcon: Node = null;
    /** 抽奖页面 */
    @property(Node)
    lottoryPage: Node = null;
    /** 提示道具数量文本 */
    @property(Node)
    lightLabel: Node = null;
    /** 提示道具广告icon */
    @property(Node)
    lightadIcon: Node = null;
    /** 提示道具按钮灰色 */
    @property(Node)
    lightBtnM: Node = null;
    /** 新手引导节点 */
    @property(Node)
    guideNode: Node = null;

    @property(Node)
    boardBg: Node = null;
    @property(Node)
    boardContainer: Node = null;


    start() {
        console.warn('on ui manager component start!!!!!', UserData.data);
        mtec.cc.adaptBackgroundNode(this.background);
        this.updateContainerLevelString();
        this.updateDialogLabel();
        this.updateCashLabel(UserData.data.curCashTotal, 0, 1);
        this.updateLotteryProgress();
        this.freshLightState();
    }

    public playBoardAnim() {
        // 用 Promise 封装 tween 动画
        const runTween = (target: any, props: any, duration: number): Promise<void> => {
            return new Promise((resolve) => {
                tween(target)
                    .to(duration, props)
                    .call(resolve) // 动画完成后执行 resolve
                    .start();
            });
        };
        // 先让背景淡出
        runTween(this.boardBg.getComponent(UIOpacity), { opacity: 0 }, 0.5)
            .then(() => {
                // 等背景淡出后，再处理 boardContainer 的动画
                return runTween(this.boardContainer, { position: v3(0, -300, 0), angle: 360, scale: v3(0, 0, 0) }, 0.5);
            })
            .then(() => {
                // 重置 boardContainer 的状态
                this.boardContainer.setPosition(v3(0, 0, 0));
                this.boardContainer.setRotationFromEuler(0, 0, 0);
                this.boardContainer.setScale(1, 1, 1);

                GameMgr.ins.isPassLevel = false;
                GameMgr.ins.startTimer();
                // 重新显示背景和 boardContainer
                return runTween(this.boardBg.getComponent(UIOpacity), { opacity: 255 }, 0.3);
            })
            .catch((error) => {
                console.error("动画执行时出错: ", error);
            });
    }
    public stopLotteryIconScaleAnim() {
        if (UserData.data.curlotteryChance == 0) {
            Tween.stopAllByTarget(this.lotteryIcon);
            this.lotteryIcon.setScale(1, 1, 1);
        }
    }
    /** 抽奖icon呼吸动画 */
    public lotteryIconScaleAnim() {
        // 停止之前的 tween 动画，避免冲突
        Tween.stopAllByTarget(this.lotteryIcon);

        // 开始新的 tween 动画
        tween(this.lotteryIcon)
            .to(0.3, { scale: v3(1.05, 1.05, 1) })
            .to(0.3, { scale: v3(1, 1, 1) })
            .union()
            .repeatForever()
            .start();
    }
    /** 刷新提示道具按钮状态 */
    public freshLightState() {
        if (UserData.data.propNum > 0) {
            if (GameMgr.ins.usePropTimes != 0) {
                this.lightLabel.active = true;
                this.lightLabel.getComponent(Label).string = '1';
                this.lightadIcon.active = false;
                this.lightBtnM.active = false;
            } else {
                this.lightLabel.active = false;
                this.lightLabel.getComponent(Label).string = '1';
                this.lightadIcon.active = false;
                this.lightBtnM.active = true;
            }
        } else {
            if (GameMgr.ins.usePropTimes != 0) {
                this.lightLabel.active = false;
                this.lightLabel.getComponent(Label).string = '';
                this.lightadIcon.active = true;
                this.lightBtnM.active = false;
            } else {
                this.lightLabel.active = false;
                this.lightLabel.getComponent(Label).string = '';
                this.lightadIcon.active = false;
                this.lightBtnM.active = true;
            }
        }
    }
    /** 更新关卡标题 */
    public updateContainerLevelString() {
        if (UserData.data.curLevel == 0) {
            this.curLevelLabel.string = 'New User Guide';
        } else {
            this.curLevelLabel.string = 'Level ' + UserData.data.curLevel;
        }
    }
    /** 更新展示词位置的string */
    updateCondLabel(str: string, color: string) {
        if (str !== '') {
            this.condContainer.active = true;
            this.condContainer.getComponent(Sprite).color = new Color().fromHEX(color);

            // 停止 condContainer 和 condContainer 的 UIOpacity 相关的所有 tween 动画
            Tween.stopAllByTarget(this.condContainer);
            Tween.stopAllByTarget(this.condContainer.getComponent(UIOpacity));

            // 设置 condContainer 的透明度和位置
            this.condContainer.getComponent(UIOpacity).opacity = 255;
            this.condContainer.setPosition(v3(0, 470, 0));

            // 将字符串中的每个字符用空格隔开
            // const spacedStr = str.split('').join(' ');
            this.condLabel.string = str;
        }
    }
    /** 关闭展示词位置容器 */
    closeCondContainer() {
        tween(this.condContainer.getComponent(UIOpacity))
            .to(0.3, { opacity: 0 })
            .start()
    }
    /** 设置答案的透明度 */
    private setAnswerWordOpacity(answerIndex: number, opacityNum: number) {
        this.answerNodeContainer.children[answerIndex].getComponent(UIOpacity).opacity = opacityNum;
    }
    /** 创建字母effect */
    async createWordEffect(selectedNodes: Node[], selectedIndexes: number[][]) {
        let answerIndex = this.findMatchingSubArrayIndex(selectedIndexes, BoardMgr.ins.correctAnswerIndexes);
        // console.log(answerIndex);

        let target_node = this.answerNodeContainer.children[answerIndex];
        // if (!target_node) {
        //     console.log(target_node);
        //     return
        // }
        let target_node_midpos = Tools.getNodeAToNodeBPoint(target_node, this.effectsContainer);
        let target_node_posArr = this.getTargetNodePosArr(selectedNodes, target_node_midpos);


        this.setAnswerWordOpacity(answerIndex, 100);


        for (let i = 0; i < selectedNodes.length; i++) {
            const word_node = selectedNodes[i];
            let word_str = BoardMgr.ins.wordStrArr[selectedIndexes[i][0]][selectedIndexes[i][1]];
            let oriEfPos = Tools.getNodeAToNodeBPoint(word_node, this.effectsContainer);
            let word = await PoolMgr.getObject('word');
            word.setScale(1, 1, 1);
            word.getComponent(UIOpacity).opacity = 255;
            word.getChildByName('lbl_word').getComponent(Label).string = word_str;
            word.setParent(this.effectsContainer);
            word.setPosition(oriEfPos);
            tween(word.getComponent(UIOpacity))
                .to(0.8, { opacity: 100 })
                .start()
            tween(word)
                .parallel(
                    tween().to(0.8, { position: target_node_posArr[i] }, { easing: 'cubicOut' }),
                    tween().to(0.8, { scale: v3(0.6, 0.6, 0.6) }, { easing: 'cubicOut' })
                )
                .call(() => {
                    PoolMgr.putObject('word', word);
                })
                .start()
        }
    }
    /** 划词展示容器摇晃---划词错误展示 */
    public condContainerShake() {

        Tween.stopAllByTarget(this.condContainer);
        Tween.stopAllByTarget(this.condContainer.getComponent(UIOpacity));
        this.condContainer.getComponent(UIOpacity).opacity = 255;
        this.condContainer.setPosition(v3(0, 470, 0));
        this.condContainer.active = true;

        tween(this.condContainer)
            .by(0.05, { position: v3(-20, 0, 0) })
            .by(0.1, { position: v3(40, 0, 0) })
            .by(0.1, { position: v3(-40, 0, 0) })
            .by(0.05, { position: v3(20, 0, 0) })
            .set({ position: v3(0, 470, 0) })
            .delay(0.2)
            .call(() => {
                tween(this.condContainer.getComponent(UIOpacity))
                    .to(0.3, { opacity: 0 })
                    .start()
                // this.condContainer.active = false;
            })
            .start()
    }
    /** 获取单个字母目标点 */
    private getTargetNodePosArr(selectedNodes: Node[], target_node_midpos: Vec3): Vec3[] {
        const nodeCount = selectedNodes.length;
        const nodeSpacing = 30; // 每个坐标间隔 30
        const positions: Vec3[] = [];

        // 计算起始点，使得所有节点围绕中心点对称分布
        const startX = target_node_midpos.x - (nodeSpacing * (nodeCount - 1)) / 2;
        const startY = target_node_midpos.y;

        for (let i = 0; i < nodeCount; i++) {
            const posX = startX + i * nodeSpacing;
            const posY = startY; // 保持 y 坐标不变
            positions.push(new Vec3(posX, posY, target_node_midpos.z)); // 保持 z 坐标不变
        }

        return positions;
    }
    /** 找到匹配的子数组，返回下标 */
    private findMatchingSubArrayIndex(arr1: number[][], arr2: number[][][]): number | null {
        for (let i = 0; i < arr2.length; i++) {
            if (this.isSubArrayEqual(arr1, arr2[i])) {
                return i; // 如果找到匹配的子数组，返回下标 i
            }
        }
        return null; // 如果没有匹配的子数组，返回 null
    }
    // 用于比较两个 number[] 数组是否相等
    private isSubArrayEqual(arr1: number[][], arr2: number[][]): boolean {
        if (arr1.length !== arr2.length) return false;
        for (let i = 0; i < arr1.length; i++) {
            if (!this.isArrayEqual(arr1[i], arr2[i])) {
                return false;
            }
        }
        return true;
    }
    private isArrayEqual(arr1: number[], arr2: number[]): boolean {
        if (arr1.length !== arr2.length) return false;
        for (let i = 0; i < arr1.length; i++) {
            if (arr1[i] !== arr2[i]) return false;
        }
        return true;
    }
    /** 更新对话框 */
    updateDialogLabel() {
        if (!GameData.data.withdrawConfig) {
            InitData.getWithdrawConf().then(conf=>GameData.data.withdrawConfig = conf);
            this.dialogLabel.node.parent.parent.active = false;
            return void 0;
        }
        this.dialogLabel.node.parent.parent.active = true;
        let config = GameData.data.withdrawConfig;
        let tarCashAmount = config.cashWithdrawConfig[0].cashAmount;
        // if (config.cashWithdrawConfig.length>2) {
        //     this.dialogLabel.node.parent.active = false;
        // }else{
        //     this.dialogLabel.node.parent.active = true;
        // }
        let needCash = tarCashAmount - UserData.data.curCashTotal
        if (needCash <= 0) {
            tarCashAmount = config.cashWithdrawConfig[1].cashAmount;
        }
        let localizedLabel = this.dialogLabel.node.getComponent(LocalizedLabel);
        localizedLabel.setTextKeyAndOption("home_diolog_Rtext", this.formatCashValue(tarCashAmount - UserData.data.curCashTotal), this.formatCashValue(tarCashAmount));
        this.dialogLabel.node.getComponent(RichTextAutoFontSize).adjustFontSize();
    }
    /** 生成一个鼓励艺术字 */
    public async createConsecutiveEffect(effPos: Vec3, totalClearedLines: number) {
        if (!effPos) {
            return
        }
        let consecutiveEff;
        let name;
        let url;
        if (totalClearedLines < 3) {
            return;
        }
        if (totalClearedLines == 3) {
            //good
            consecutiveEff = await PoolMgr.getObject('good');
            name = 'good';
            url = Url.AUDIO.SFX17;
        } else if (totalClearedLines == 4) {
            //great
            consecutiveEff = await PoolMgr.getObject('great');
            name = 'great';
            url = Url.AUDIO.SFX18;
        } else if (totalClearedLines == 5) {
            //excellent
            consecutiveEff = await PoolMgr.getObject('excellent');
            name = 'excellent';
            url = Url.AUDIO.SFX19;
        } else if (totalClearedLines == 6) {
            //amazing
            consecutiveEff = await PoolMgr.getObject('amazing');
            name = 'amazing';
            url = Url.AUDIO.SFX20;
        } else if (totalClearedLines == 7) {
            //unbelievable
            consecutiveEff = await PoolMgr.getObject('unbelievable');
            name = 'unbelievable';
            url = Url.AUDIO.SFX21;
        }
        AudioMgr.ins.playOneShot(url, 1);
        consecutiveEff.setParent(this.effectsContainer);
        consecutiveEff.setPosition(effPos);
        consecutiveEff.getComponent(UIOpacity).opacity = 255;
        tween(consecutiveEff)
            .delay(0.5)
            .to(0.5, { position: v3(0, 50, 0) })
            .call(() => {
                PoolMgr.putObject(name, consecutiveEff)
            })
            .start()

        tween(consecutiveEff.getComponent(UIOpacity))
            .delay(0.5)
            .to(0.5, { opacity: 0 })
            .start()
        // consecutiveEff.qtJumpDistance(new Vec3(Tools.randInt(-400, 400), -Tools.randInt(1000, 1500), 0), Tools.randInt(1000, 1200), 1, 1)
        //     .call(() => {
        //         PoolMgr.putObject(name, consecutiveEff)
        //     })
        //     .start();
    }
    /** 展示 飞钱效果*/
    public async shwoGetCashEffect(effectpos: Vec3) {
        if (!effectpos) {
            return
        }
        let tarCashPos = Tools.getNodeAToNodeBPoint(this.tarCashIcon, this.effectsContainer);
        effectpos.add(v3(0, -100, 0));
        for (let i = 0; i < 6; i++) {
            setTimeout(async () => {
                let casheffect = await PoolMgr.getObject('casheffect');
                casheffect.setParent(this.effectsContainer);
                casheffect.setPosition(effectpos);
                casheffect.setScale(0.3, 0.3, 1)
                let midpos = this.getRandomPositionAround(effectpos, 200);
                tween(casheffect)
                    .to(0.7, { scale: v3(0.5, 0.5, 1) })
                    .start();
                tween(casheffect)
                    .to(0.1, { position: midpos })
                    .delay(0.1)
                    .to(0.5, { position: tarCashPos })
                    .call(() => {
                        AudioMgr.ins.playOneShot(Url.AUDIO.SFX7, 1);
                        PoolMgr.putObject('casheffect', casheffect);
                        tween(this.tarCashIcon)
                            .to(0.05, { scale: v3(1.1, 1.1, 1) })
                            .to(0.05, { scale: v3(1, 1, 1) })
                            .start();
                    })
                    .start();
            }, i * 100);
        }

    }
    /** 左上角加钱 */
    public async createLabelTip1(_cashAmount) {
        let tarCashPos = Tools.getNodeAToNodeBPoint(this.tarCashIcon, this.effectsContainer);
        let labelTip1 = await PoolMgr.getObject('labelTip1');
        labelTip1.getComponent(Label).string = '+' + this.formatCashValue(_cashAmount);
        labelTip1.getComponent(UIOpacity).opacity = 255;
        labelTip1.setParent(this.effectsContainer);
        labelTip1.setPosition(tarCashPos.add(v3(250, 0, 0)));
        tween(labelTip1)
            .by(0.5, { position: v3(0, 50, 0) })
            .delay(0.2)
            .removeSelf()
            .start()
        tween(labelTip1.getComponent(UIOpacity))
            .delay(0.5)
            .to(0.2, { opacity: 0 })
            .start()

    }
    /** 更新钱数 */
    public updateCashLabel(newCashTotal: number, amount?: number, isstart = 0) {
        if (!newCashTotal) {
            return
        }
        // console.log(newCashTotal, UserData.data.curCashTotal);

        amount = amount ?? (newCashTotal - UserData.data.curCashTotal);

        // console.log(amount);
        // this.scheduleOnce(() => {
        // if (UserData.data.curCashTotal >= GlobalData.wdlevelCahs) {
        //     ClientAPI.Point(NCPoint.SYMBOLENOUGH, { userid: UserData.data.userId });
        // }
        const currentCashString = this.curCashLabel.string || "0";
        const currentCash = parseFloat(currentCashString.replace(/[^\d.-]/g, '')) || 0;
        const duration = 0.25;
        if (currentCash === newCashTotal) {
            this.curCashLabel.string = this.formatCashValue(newCashTotal);
            return;
        }
        if (isstart == 1) {
            this.curCashLabel.string = this.formatCashValue(newCashTotal);
        } else {
            // 启动 tween，并确保在 onUpdate 中进行更新
            tween({ value: currentCash })
                .to(duration, { value: newCashTotal }, {
                    onUpdate: (target: { value: number }) => {
                        let formattedValue = this.formatCashValue(target.value);
                        // console.log(formattedValue);
                        this.curCashLabel.string = formattedValue;
                    }
                })
                .start();
        }
        UserData.data.curCashTotal = newCashTotal;
        UIMgr.ins.updateDialogLabel();
        // }, 0.5);
        this.scheduleOnce(() => {
            if (isstart == 0) {
                this.createLabelTip1(amount);
            }
        }, 1)
    }
    /** 格式化钱数字符串 */
    public formatCashValue(value: number): string {
        if (!GameData.data.confCountry) {
            ServiceAPI.ConfCountry(UserData.data.country)
                .then(res => GameData.data.confCountry = res);
        }
        let { round, front, thousand, point, symbol } = GameData.data.confCountry ?? {};
        // let round = GameData.data.confCountry.round; // 是否需要取整：1-需要，0-不需要
        // let front = GameData.data.confCountry.front; // 货币格式符号是否前置：1-前置，0-后置
        // let thousand = GameData.data.confCountry.thousand; // 千位符号：1-".", 2-",", 3-" "
        // let point = GameData.data.confCountry.point; // 小数点：1-".", 2-",", 3-" "
        // let symbol = GameData.data.confCountry.symbol;
        round = round ?? 1;
        front = front ?? 1;
        thousand = thousand ?? 2;
        point = point ?? 1;
        symbol = symbol ?? '$';


        // 取整处理
        if (round === 1) {
            value = Math.round(value);
        }

        // 小数点符号替换
        let decimalSymbol = point === 1 ? '.' : point === 2 ? ',' : ' ';
        let thousandSymbol = thousand === 1 ? '.' : thousand === 2 ? ',' : ' ';

        // 格式化数字
        let parts = value.toFixed(2).split('.');
        let integerPart = parts[0];
        let decimalPart = parts[1];

        // 如果小数部分为 "0" 或 "00"，则只显示整数部分，否则保留小数部分
        let formattedValue = decimalPart === "00" || (decimalPart.length === 1 && decimalPart[0] === '0')
            ? integerPart
            : `${integerPart}${decimalSymbol}${decimalPart.replace(/0+$/, '')}`;

        // 添加千位分隔符
        integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSymbol);

        // 根据前置/后置符号设置
        if (front === 1) {
            return `${symbol}${formattedValue}`;
        } else {
            return `${formattedValue}${symbol}`;
        }
    }
    public getRandomPositionAround(origin: Vec3, radius: number): Vec3 {
        // 确保最小半径不小于50
        const minRadius = 50;
        const finalRadius = Math.max(minRadius, radius);

        // 随机生成角度（以弧度为单位）
        const angle = Math.random() * 2 * Math.PI;

        // 在[minRadius, finalRadius]范围内生成距离
        const distance = minRadius + Math.random() * (finalRadius - minRadius);

        // 计算新位置的偏移量
        const offsetX = Math.cos(angle) * distance;
        const offsetY = Math.sin(angle) * distance;

        // 返回新位置
        return new Vec3(origin.x + offsetX, origin.y + offsetY, origin.z);
    }
    //  生成一个tip吐司、
    public async createOneTipToast(str: string, insert: string = null) {
        let tip: Node = await PoolMgr.getObject('toast');
        tip.setParent(this.effectsContainer);
        tip.setPosition(v3(0, 0, 0));
        tip.getComponent(UIOpacity).opacity = 255;
        let tiplabel = tip.children[0].getComponent(Label)
        let localizedLabel = tiplabel.node.getComponent(LocalizedLabel);
        localizedLabel.setTextKeyAndOption(str, insert);

        tween(tip)
            .delay(0.5)
            .to(0.5, { position: v3(0, 50, 0) })
            .call(() => {
                PoolMgr.putObject('toast', tip)
            })
            .start()

        tween(tip.getComponent(UIOpacity))
            .delay(0.5)
            .to(0.5, { opacity: 0 })
            .start()
    }
    /** 更新抽奖进度 */
    public async updateLotteryProgress() {
        // console.log('更新抽奖进度条');

        // console.log(!GameData.data.drawProcessConfig, GameData.data.drawProcessConfig);

        if (!GameData.data.drawProcessConfig) {
            try {
                const res = await ServiceAPI.ConfCommon(UserData.data.userId);
                console.log('API response:', res);

                // 如果 res?.drawProcessConfig 存在则使用，否则使用一个默认值
                GameData.data.drawProcessConfig = res?.drawProcessConfig ?? [
                    { "startCount": 0, "endCount": 1, "skipCount": 5 },
                    { "startCount": 2, "endCount": 12, "skipCount": 20 },
                    { "startCount": 13, "endCount": 999999999, "skipCount": 30 }
                ];
            } catch (error) {
                console.log('Error fetching ConfCommon:', error);

                // 设置默认值，确保在请求失败时也有数据
                GameData.data.drawProcessConfig = [
                    { "startCount": 0, "endCount": 1, "skipCount": 5 },
                    { "startCount": 2, "endCount": 12, "skipCount": 20 },
                    { "startCount": 13, "endCount": 999999999, "skipCount": 30 }
                ];
            }
        }
        if (UserData.data.curlotteryChance > 0) {
            this.lotteryIconScaleAnim();
        } else {
            this.stopLotteryIconScaleAnim();
        }
        const curLotteryTimes = UserData.data.curGetLotteryTimes;
        // console.log(curLotteryTimes);
        for (let rule of GameData.data.drawProcessConfig) {
            if (curLotteryTimes >= rule.startCount && curLotteryTimes <= rule.endCount) {
                const progressValue = UserData.data.tempPassLevelTimes_lottery / rule.skipCount;
                this.lotteryProgress.fillRange = progressValue;
                this.lotteryProgressLabel.string = `${UserData.data.tempPassLevelTimes_lottery}/${rule.skipCount}`;

                let localizedLabel = this.lottoryLabel.node.getComponent(LocalizedLabel);
                localizedLabel.setTextKeyAndOption("home_lottery_pro_Rtext", rule.skipCount - UserData.data.tempPassLevelTimes_lottery);

                if (UserData.data.tempPassLevelTimes_lottery >= rule.skipCount) {
                    UserData.data.curlotteryChance++;
                    UserData.data.curGetLotteryTimes++;
                    UserData.data.tempPassLevelTimes_lottery = 0;
                    this.updateLotteryProgress();

                    this.homePage.showLotteryPage();

                }
                break;
            }
        }

    }


}

